package com.yale.spring.cloud.code.service;

import com.yale.spring.cloud.commons.OpenResponse;
import com.yale.spring.cloud.commons.OpenResponseCode;
import com.yale.spring.cloud.commons.model.MailInfo;
import com.yale.spring.cloud.feigin.api.CodeService;
import com.yale.spring.cloud.feigin.api.MailService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author yale
 */
@DubboService
public class CodeServiceImpl implements CodeService {

    @DubboReference
    private MailService mailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String generateCode(String mailTo) {
        String code=genCode();
        MailInfo mailInfo=new MailInfo();
        mailInfo.setTo(mailTo);
        mailInfo.setContent(code);
        mailInfo.setSubject("测试邮件");
        mailService.sendEmail(mailInfo);
        //验证码10分钟有效
        redisTemplate.opsForValue().set(mailTo+"_"+"code",Integer.valueOf(code),600, TimeUnit.SECONDS);
        return code;
    }

    @Override
    public Boolean verifyCode(String mail, String code) {
        String codeSend=String.valueOf(redisTemplate.opsForValue().get(mail+"_code"));
        if(StringUtils.isEmpty(codeSend)|| !code.equals(codeSend)){
            return false;
        }
        return true;
    }

    private String genCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
